// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#include <melon/init/init.h>
#include <turbo/flags/flag.h>
#include <turbo/log/logging.h>
#include <thrift/lib/cpp2/server/ThriftServer.h>
#include <pollux/functions/prestosql/registration/registration_functions.h>
#include <pollux/functions/remote/server/remote_function_service.h>

/// This file generates a binary only meant for testing. It instantiates a
/// remote function server able to serve all Presto functions, and is used
/// to ensure that the client instrumentation of remote function execution works
/// as expected.
///
/// It currently listens on a local unix domain socket controlled by the flag
/// below.

TURBO_FLAG(std::string,
    uds_path,
    "/tmp/remote.socket",
    "Unix domain socket used by the thrift server.");

TURBO_FLAG(std::string,
    function_prefix,
    "json.test_schema.",
    "Prefix to be added to the functions being registered");

using namespace ::kumo::pollux;
using ::apache::thrift::ThriftServer;

int main(int argc, char *argv[]) {
    melon::Init init{&argc, &argv, false};
    memory::MemoryManager::initialize({});
    //FLAGS_logtostderr = true;

    // Always registers all Presto functions and make them available under a
    // certain prefix/namespace.
    KLOG(INFO) << "Registering Presto functions";
    functions::prestosql::registerAllScalarFunctions(FLAGS_function_prefix);

    melon::SocketAddress location{
        melon::SocketAddress::makeFromPath(FLAGS_uds_path)
    };

    KLOG(INFO) << "Initializing thrift server";
    auto handler = std::make_shared<functions::RemoteFunctionServiceHandler>();
    auto server = std::make_shared<ThriftServer>();
    server->setInterface(handler);
    server->setAddress(location);
    server->serve();

    KLOG(INFO) << "Shutting down.";
    return 0;
}
